from flask import Blueprint
from flask import render_template, request, redirect, session, url_for
from sqlalchemy import or_

from LoginModels import LoginForm
from RegisterModels import registerForm
from blog.models import Article, Comment
from exit import db
from user.models import User
from datetime import datetime, timedelta

user_bp = Blueprint('user', __name__, url_prefix='/user')

#注册
@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    # 导入loginForm类，并创建对象
    # 需要接受表单传递过来的数据，对数据进行验证
    myform = registerForm(request.form)

    if request.method == 'POST':
        if myform.validate():
            username = request.form.get('username')
            password = request.form.get('password')
            passwords = request.form.get('passwords')
            phone = request.form.get('uphone')
            print(myform.errors)
            if password == passwords:
                user = User(username, password, phone)
                db.session.add(user)
                db.session.commit()
                return redirect(url_for('user.login'))
            else:
                return render_template('register.html', myform=myform)
        else:
            return render_template('register.html', myform=myform)
    else:
        return render_template('register.html', myform=myform)

# 登录
@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    # 导入loginForm类，并创建对象
    # 需要接受表单传递过来的数据，对数据进行验证
    myform = LoginForm(request.form)
    if request.method == 'POST':
        if myform.validate():
            username = request.form.get('username')
            password = request.form.get('password')
            user = User.query.filter(or_(User.uname == username, User.uphone == username)).first()
            if user:
                if user.upsw == password:

                    #cookie会话机制
                    #设置cookie会话机制
                    # response = redirect(url_for('blog.index'))
                    # time = datetime.now() + timedelta(days=1) #设置缓存时长
                    # response.set_cookie('username', user.uname, expires=time)
                    # return response

                    #设置session会话机制，字典格式
                    session['username'] = username
                    return redirect(url_for('blog.index'))
            else:
                return render_template('login.html', myform=myform)
        else:
            return render_template('login.html', myform=myform)
    else:
        return render_template('login.html', myform=myform)

# 退出登录
@user_bp.route('/exit')
def exit():
    # cookie退出登录
    # response = redirect(url_for('blog.index'))
    # response.delete_cookie('username')
    # return response

    #session退出登录
    session.pop('username')
    return redirect(url_for('blog.index'))

#用户的个人信息
@user_bp.route('/infomation')
def infomation():
    # 根据当前登录的用户，获取该用户的信息
    user = User.query.filter(User.uname == session.get('username')).first()

    return render_template('infomation.html', user=user)

#修改用户名
@user_bp.route('/change_name', endpoint='changename', methods=['POST'])
def chang_name():
    # print(request.form)  #ImmutableMultiDict([('username', 'jiaoyulong')])
    # 根据数据，先验证昵称是否修改了
    username = request.form.get('username')
    if username != session.get('username'):
        #在数据库中查询
        user = User.query.filter(User.uname == username).first()

        # print(user) #当你修改后的用户名和其他用户名不重复的情况下，返回None，否则返回该用户名的对象

        if user is None:
            # 这个用户名不存在
            # 数据库中也应该有相应的修改操作
            # 根据session存储的用户名，找到登录用户，修改用户的昵称， 并修改会话机制中的昵称
            original_user = User.query.filter(User.uname == session.get('username')).first()
            original_user.uname = username
            db.session.commit()

            #修改session中的username
            session['username'] =username
            return {'code': 2001, 'mesage': '修改成功'}
        else:
            return {'code': 2002, 'message': '该用户名已经存在！'}

    else:
        return {'code': 2000, 'message': '昵称没有发生修改'}

#修改密码
@user_bp.route('/change_psw', endpoint='changepsw', methods=['POST'])
def change_psw():
    # print(request.form)
    username = request.form.get('username')
    upsw = request.form.get('upsw')
    if username == session.get('username'):
        original_user = User.query.filter(User.uname == session.get('username')).first()
        original_user.upsw = upsw
        db.session.commit()
        return {'code': 2001, 'message': '修改成功'}
    else:
        return {'code': 2000, 'message': '没有修改密码'}

#修改手机号
@user_bp.route('/change_phone', endpoint='phone', methods=['POST'])
def change_phone():
    print(request.form)
    username = request.form.get('uname')
    # print(username)
    # print(session.get('username'))
    uphone = request.form.get('uphone')
    if username == session.get('username'):
        user = User.query.filter(User.uphone == uphone).first()
        print(user)
        if user is None:
            original_phone = User.query.filter(User.uname == session.get('username')).first()
            # print(original_phone)
            original_phone.uphone = uphone
            db.session.commit()
            return {'code': 2001, 'message': '修改成功'}
        else:
            return {'code': 2000, 'message': '手机号已经存在'}
    else:
        return {'code': 2002, 'message': '没有修改手机号'}

#我的博客
@user_bp.route('/myarticle')
def myarticle():
    user = User.query.filter(User.uname == session.get('username')).first()
    return render_template('myarticle.html', myarticles = user.article)

#获取我的博客的点赞量
@user_bp.route('/mylikenum')
def mylikenum():
    # print(request.args)
    aid = request.args.get('aid')
    # 通过主键获取文章对象
    article = Article.query.get(aid)
    article.likenum
    return {'code':2000, 'likenum': article.likenum, 'aid': article.aid}

#我的评论
@user_bp.route('/mycomment')
def mycomment():
    user = User.query.filter(User.uname == session.get('username')).first()
    return render_template('mycomments.html', mycomments=user.comments)

#删除我的评论
@user_bp.route('/delcomment')
def delcomment():
    # print(request.args)
    cid = request.args.get('cid')
    # 根据cid获取评论
    comment = Comment.query.get(cid)
    #删除数据库中的评论
    db.session.delete(comment)
    db.session.commit()
    return redirect(url_for('user.mycomment'))


 #删除我的博客
@user_bp.route('/delarticle')
def delarticle():
    aid = request.args.get("aid")
    #获取博客对象
    article = Article.query.get(aid)
    #获取该篇博客的所有评论
    # print(article.comments)
    # 删除该篇文章的所有评论，然后再删除该篇文章
    for com in article.comments:
        db.session.delete(com)
    #在数据库中删除文章
    db.session.delete(article)
    db.session.commit()
    return redirect(url_for('user.myarticle'))